<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Babylon.js AssetContainer 示例</title>
    <script src="babylon.js"></script>
    <script src="babylon.gui.min.js"></script>
    <script src="babylonjs.loaders.min.js"></script>
    <style>
        body { margin: 0; overflow: hidden; }
        canvas { width: 100%; height: 100%; }
        .controls {
            position: absolute;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            display: flex;
            gap: 10px;
            z-index: 10;
        }
        button {
            padding: 10px 15px;
            font-size: 16px;
            cursor: pointer;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
        }
        button:hover {
            background-color: #45a049;
        }
    </style>
</head>
<body>
    <canvas id="renderCanvas"></canvas>
    <div class="controls">
        <button id="addModelBtn">添加模型</button>
        <button id="removeModelBtn">移除模型</button>
        <button id="cloneModelBtn">克隆模型</button>
        <button id="disposeBtn">释放资源</button>
    </div>

    <script>
        // 初始化引擎和场景
        const canvas = document.getElementById('renderCanvas');
        const engine = new BABYLON.Engine(canvas, true);
        
        // 创建场景的函数
        var createScene = function() {
            const scene = new BABYLON.Scene(engine);
            scene.clearColor = new BABYLON.Color3(0.8, 0.8, 0.8);
            
            // 添加相机
            const camera = new BABYLON.ArcRotateCamera(
                "camera", 
                -Math.PI / 2, 
                Math.PI / 2.5, 
                10, 
                BABYLON.Vector3.Zero(), 
                scene
            );
            camera.attachControl(canvas, true);
            
            // 添加光源
            const light = new BABYLON.HemisphericLight(
                "light", 
                new BABYLON.Vector3(0, 1, 0), 
                scene
            );
            light.intensity = 0.7;
            
            // 创建GUI系统用于显示网格信息
            const advancedTexture = BABYLON.GUI.AdvancedDynamicTexture.CreateFullscreenUI("UI");
            
            // 创建信息面板
            const panel = new BABYLON.GUI.StackPanel();
            panel.width = "250px";
            panel.top = "10px";
            panel.left = "10px";
            panel.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
            panel.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP;
            panel.background = "rgba(0, 0, 0, 0.7)";
            panel.paddingTop = "10px";
            panel.paddingLeft = "10px";
            panel.paddingRight = "10px";
            panel.paddingBottom = "10px";
            panel.isVisible = false;
            advancedTexture.addControl(panel);
            
            // 面板标题
            const header = new BABYLON.GUI.TextBlock();
            header.text = "加载的网格";
            header.color = "white";
            header.fontSize = 18;
            header.height = "30px";
            header.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
            panel.addControl(header);
            
            // 分隔线
            const line = new BABYLON.GUI.Line();
            line.x1 = 0;
            line.y1 = 0;
            line.x2 = 230;
            line.y2 = 0;
            line.color = "white";
            line.thickness = 1;
            panel.addControl(line);
            
            // 网格列表容器
            const meshList = new BABYLON.GUI.StackPanel();
            meshList.isVertical = true;
            panel.addControl(meshList);
            
            // 用于存储AssetContainer和实例的变量
            let assetContainer = null;
            let currentInstances = [];
            let modelPosition = 0;
            
            // 更新网格信息显示
            function updateMeshInfo(meshes) {
                // 清空现有列表
                while (meshList.children.length > 0) {
                    meshList.removeControl(meshList.children[0]);
                }
                
                // 添加网格数量
                const countText = new BABYLON.GUI.TextBlock();
                countText.text = "网格数量: " + meshes.length;
                countText.color = "white";
                countText.fontSize = 14;
                countText.height = "25px";
                countText.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
                meshList.addControl(countText);
                
                // 添加所有网格名称
                meshes.forEach((mesh, index) => {
                    const meshText = new BABYLON.GUI.TextBlock();
                    meshText.text = (index + 1) + ". " + mesh.name;
                    meshText.color = "white";
                    meshText.fontSize = 14;
                    meshText.height = "25px";
                    meshText.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
                    meshList.addControl(meshText);
                });
                
                panel.isVisible = meshes.length > 0;
            }
            
            // 从URL加载AssetContainer（使用Babylon.js示例模型）
            function loadAssetContainer() {
                // 使用Babylon.js官方示例模型
                BABYLON.SceneLoader.LoadAssetContainer(
                    "https://playground.babylonjs.com/scenes/",
                    "skull.babylon",
                    scene,
                    function(container) {
                        assetContainer = container;
                        console.log("模型加载完成");
                        document.getElementById('addModelBtn').disabled = false;
                    },
                    null,
                    function(error) {
                        console.error("加载模型时出错:", error);
                    }
                );
            }
            
            // 添加模型到场景
            document.getElementById('addModelBtn').addEventListener('click', function() {
                if (!assetContainer) return;
                
                // 实例化模型并添加到场景
                const instances = assetContainer.instantiateModelsToScene(false);
                
                // 移动实例位置，避免重叠
                const positionOffset = modelPosition * 3;
                for(var mesh of instances.rootNodes) {
					mesh.position.x += positionOffset;
				}
                
                currentInstances.push(...instances.rootNodes);
                modelPosition++;
                
                // 更新网格信息
                updateMeshInfo(currentInstances);
            });
            
            // 从场景移除模型
            document.getElementById('removeModelBtn').addEventListener('click', function() {
                if (currentInstances.length === 0) return;
                
                // 移除最后添加的实例
                const lastInstance = currentInstances.pop();
                lastInstance.dispose();
                
                // 更新网格信息
                updateMeshInfo(currentInstances);
            });
            
            // 克隆当前模型
            document.getElementById('cloneModelBtn').addEventListener('click', function() {
                if (currentInstances.length === 0 || !assetContainer) return;
                
                // 克隆模型并添加到场景
                const instances = assetContainer.instantiateModelsToScene(false);
                
                // 移动克隆体位置
                const positionOffset = modelPosition * 3;
                for(var mesh of instances.rootNodes) {
					mesh.position.x += positionOffset;
				}
                
                currentInstances.push(...instances.rootNodes);
                modelPosition++;
                
                // 更新网格信息
                updateMeshInfo(currentInstances);
            });
            
            // 释放资源
            document.getElementById('disposeBtn').addEventListener('click', function() {
                if (!assetContainer) return;
                
                // 移除所有实例
                for(var mesh of currentInstances) {
					mesh.dispose();
				}
                currentInstances = [];
                
                // 释放AssetContainer
                assetContainer.dispose();
                assetContainer = null;
                
                // 禁用按钮
                document.getElementById('addModelBtn').disabled = false;
                document.getElementById('cloneModelBtn').disabled = true;
                
                // 更新网格信息
                updateMeshInfo([]);
                console.log("资源已释放");
            });
            
            // 初始加载模型
            loadAssetContainer();
            
            return scene;
        };
        
        // 创建场景
        const scene = createScene();
        
        // 渲染循环
        engine.runRenderLoop(function() {
            scene.render();
        });
        
        // 响应窗口大小变化
        window.addEventListener('resize', function() {
            engine.resize();
        });
    </script>
</body>
</html>    